package com.hzgj.bcl.soa.interceptor;

import com.hzgj.bcl.soa.rpc.message.Message;

import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class FastSerialization implements Serialization {
    static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration();
    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public String getName() {
        return "fast";
    }

    @Override
    public byte getId() {
        return 22;
    }

    @Override
    public byte[] write(Message message) throws Exception {
        ByteArrayOutputStream output = new ByteArrayOutputStream(8092);
        FSTObjectOutput out = conf.getObjectOutput(output);
        try {
            out.writeObject(message.getPayload());
            out.flush();
        } catch (Exception e) {
            logger.error("FastSerialization write", e);
            throw e;
        } finally {
            try {
                output.close();
            } catch (IOException e) {
                logger.error("{}", e);
            }
        }
        return output.toByteArray();
    }

    @Override
    public Object read(Message message) throws Exception {
        ByteArrayInputStream input = new ByteArrayInputStream((byte[]) message.getPayload());
        FSTObjectInput in = conf.getObjectInput(input);
        try {
            return in.readObject();
        } catch (Exception e) {
            logger.error("FastSerialization read", e);
            throw e;
        } finally {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
}
